package com.hiray.restcache

import android.content.Intent
import android.os.Bundle
import android.view.View
import androidx.appcompat.app.AppCompatActivity
import com.hiray.restcache.api.RestApi
import com.hiray.restcache.api.RestApiHelper
import com.hiray.restcache.api.res.LoginRequest
import com.hiray.restcache.helper.Helper
import com.zmy.rxcache.RxCache
import es.dmoral.toasty.Toasty
import io.reactivex.android.schedulers.AndroidSchedulers
import io.reactivex.schedulers.Schedulers
import kotlinx.android.synthetic.main.activity_main.*

class MainActivity : AppCompatActivity() {

    val TAG = "MainActivity"

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)
        supportActionBar?.title = "登录"
    }

    fun login(view: View) {

        val username = username.text.toString().trim()
        val password = password.text.toString().trim()

        val originApi = RestApiHelper.create()


        val restApi = RxCache.Builder()
            .setCacheDir(cacheDir)
            .build()
            .create(originApi, RestApi::class.java)


        val subscribe =
            restApi
                .login(LoginRequest(username, password))
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe({

                    Helper.token(it.data.data.token)

                    startActivity(Intent(this, TextActivity::class.java))
                }, {
                    Toasty.info(
                        this,
                        it.message ?: ""
                    ).show()
                    it.printStackTrace()
                }, {

                })
    }


}